import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Space, Checkbox, Radio } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import styles from './ChoicesForm.module.css';

// interface Choice {
//   id: string;
//   content: string;
//   isCorrect?: boolean;
// }

// interface Props {
//   initialValues?: {
//     choices?: Choice[];
//     correct_answers?: string[];
//   };
// }

const ChoicesForm: React.FC = () => {
  // 从父组件获取表单实例
  const parentForm = Form.useFormInstance();
  const questionType = parentForm.getFieldValue('type');
  const [selectedAnswers, setSelectedAnswers] = useState<string[]>([]);
  const correctAnswers = parentForm.getFieldValue('correct_answers') || [];
  // 初始化时，设置选中的正确答案
  //const correctAnswers = initialValues?.correct_answers || [];
  // console.log('ChoicesForm初始化 - 正确答案:', correctAnswers);
  
  return (
    <div className={styles.choicesContainer}>
      <h3>选项设置</h3>
      
      {/* 表头 */}
      <div className={styles.headerRow}>
        <div className={styles.deleteColumn}></div>
        <div className={styles.idColumn}>选项标识</div>
        <div className={styles.contentColumn}>选项内容</div>
        <div className={styles.correctColumn}>正确答案</div>
      </div>
      
      {/* 选项列表 */}
      <Form.List name="choices">
        {(fields, { add, remove }) => (
          <>
            {fields.map((field) => {
              // 获取当前所有选项和正确答案
              const choices = parentForm.getFieldValue('choices') || [];
              const choice = choices[field.name];
              console.log(correctAnswers);
              
              // 检查此选项是否为正确答案
              const isCorrect = choice && choice.id && correctAnswers.includes(choice.id);
              
              return (
                <Space key={field.key} className={styles.choiceItem} align="baseline">
                  <MinusCircleOutlined
                    className={styles.deleteButton}
                    onClick={() => {
                      // 删除选项时，同时从正确答案中移除
                      const choice = choices[field.name];
                      if (choice && choice.id) {
                        const newSelectedAnswers = selectedAnswers.filter(id => id !== choice.id);
                        setSelectedAnswers(newSelectedAnswers);
                        parentForm.setFieldsValue({ correct_answers: newSelectedAnswers });
                      }
                      remove(field.name);
                    }}
                  />
                  
                  <Form.Item
                    key={`id-${field.key}`}
                    name={[field.name, 'id']}
                    rules={[{ required: true, message: '请输入选项ID' }]}
                  >
                    <Input 
                      placeholder="选项ID (如: A, B, C...)" 
                      style={{ width: 120 }}
                      onChange={(e) => {
                        // 当ID变化时，需要更新正确答案列表
                        const oldChoice = choices[field.name];
                        if (oldChoice && oldChoice.id && selectedAnswers.includes(oldChoice.id)) {
                          const newSelectedAnswers = selectedAnswers.filter(id => id !== oldChoice.id);
                          if (e.target.value) {
                            newSelectedAnswers.push(e.target.value);
                          }
                          setSelectedAnswers(newSelectedAnswers);
                          parentForm.setFieldsValue({ correct_answers: newSelectedAnswers });
                        }
                      }}
                    />
                  </Form.Item>
                  
                  <Form.Item
                    key={`content-${field.key}`}
                    name={[field.name, 'content']}
                    rules={[{ required: true, message: '请输入选项内容' }]}
                  >
                    <Input placeholder="选项内容" style={{ width: 400 }} />
                  </Form.Item>
                  
                  {questionType === 'single' ? (
                    <Radio
                      checked={isCorrect}
                      onChange={(e) => {
                        if (!choice || !choice.id) return;
                        
                        if (e.target.checked) {
                          // 单选题只能选一个正确答案
                          const newSelectedAnswers = [choice.id];
                          setSelectedAnswers(newSelectedAnswers);
                          parentForm.setFieldsValue({ correct_answers: newSelectedAnswers });
                        }
                      }}
                    />
                  ) : (
                    <Checkbox
                      checked={isCorrect}
                      onChange={(e) => {
                        if (!choice || !choice.id) return;
                        
                        let newSelectedAnswers = [...selectedAnswers];
                        if (e.target.checked) {
                          // 添加到正确答案
                          if (!newSelectedAnswers.includes(choice.id)) {
                            newSelectedAnswers.push(choice.id);
                          }
                        } else {
                          // 从正确答案中移除
                          newSelectedAnswers = newSelectedAnswers.filter(id => id !== choice.id);
                        }
                        
                        setSelectedAnswers(newSelectedAnswers);
                        parentForm.setFieldsValue({ correct_answers: newSelectedAnswers });
                      }}
                    />
                  )}
                </Space>
              );
            })}
            
            <Button
              type="dashed"
              onClick={() => {
                const id = String.fromCharCode(65 + fields.length);
                add({ id, content: '' });
              }}
              block
              icon={<PlusOutlined />}
            >
              添加选项
            </Button>
          </>
        )}
      </Form.List>
      
      {/* 隐藏字段用于存储正确答案 */}
      <Form.Item name="correct_answers" hidden>
        <Input />
      </Form.Item>
    </div>
  );
};

export default ChoicesForm;
